import 'package:TikTok/HomePage.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoSwitchPage extends StatefulWidget {
  @override
  _VideoSwitchPageState createState() => _VideoSwitchPageState();
}

class _VideoSwitchPageState extends State<VideoSwitchPage> {
  late VideoPlayerController _controller;
  int _currentVideoIndex = 0;
  final List<String> _videoPaths = [
    'assets/video1.mp4',
    // 'assets/video2.mp4',
  ];

  @override
  void initState() {
    super.initState();
    _initializeAndPlay(_videoPaths[_currentVideoIndex]);
    
    // 将视频控制器传递给HomePage
    WidgetsBinding.instance.addPostFrameCallback((_) {
      HomePage.setVideoController(_controller);
    });

    // WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((_) {
    //   showDialog(
    //       context: context,
    //       barrierDismissible: false,
    //       builder: (_) {
    //         return const ToChatDialog();
    //       });
    // });
  }

  Future<void> _initializeAndPlay(String path) async {
    final sdkInt = (await DeviceInfoPlugin().androidInfo).version.sdkInt;
    if (sdkInt <= 29) {
      _controller = VideoPlayerController.asset(path, viewType: VideoViewType.platformView);
    } else {
      _controller = VideoPlayerController.asset(path);
    }

    await _controller.initialize();
    _controller.setLooping(false); // 不循环，播放完自动切换
    _controller.addListener(_videoListener);
    _controller.play();
    setState(() {});
  }

  void _videoListener() {
    if (_controller.value.position >= _controller.value.duration &&
        !_controller.value.isPlaying) {
      _switchVideo();
    }
  }

  Future<void> _switchVideo() async {
    _controller.removeListener(_videoListener);
    await _controller.pause();
    await _controller.dispose();
    //_currentVideoIndex = 1 - _currentVideoIndex;
    _currentVideoIndex = 0 - _currentVideoIndex;
    await _initializeAndPlay(_videoPaths[_currentVideoIndex]);
    
    // 更新HomePage中的视频控制器引用
    HomePage.setVideoController(_controller);
  }

  Future<void> showGetDialog() async {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) {
        return WillPopScope(
          onWillPop: () async => false,
          child: const ToChatDialog(),
        );
      },
    );
  }

  @override
  void dispose() {
    _controller.removeListener(_videoListener);
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    MediaQueryData mediaQueryData = MediaQuery.of(context);
    return Scaffold(
      body: _controller.value.isInitialized
          ? SafeArea(
              top: false,
              child: GestureDetector(
                onTap: () {
                  showGetDialog();
                },
                onDoubleTap: () {
                  showGetDialog();
                },
                onPanEnd: (_) {
                  showGetDialog();
                },
                child: Container(
                    color: Colors.black,
                    padding: EdgeInsets.only(top: 15),
                    alignment: Alignment.center,
                    child: FittedBox(
                      fit: BoxFit.cover,
                      child: SizedBox(
                        width: mediaQueryData.size.width,
                        height: mediaQueryData.size.height - mediaQueryData.padding.top,
                        child: VideoPlayer(_controller),
                      ),
                    )),
              ),
            )
          : Center(child: CircularProgressIndicator()),
    );
  }
}
